<template>
  <div>
    <el-dialog
      class="detail-dialog"
      :visible.sync="dialogVisible"
      :fullscreen="true"
      :append-to-body="true"
      :show-close="false">
      <div slot="title" class="nav-bar">
        <el-button class="back" type="text" @click="dialogVisible=false;">{{gobackText}}</el-button>
        <span class="nav-wrapper">
          <div class="menu-wrapper" v-for="(menu, index) in menuList" :key="index">
            <div class="menu" :class="{'active': curMenu===index}" @click="changePage(index)">{{menu}}</div>
          </div>
        </span>
      </div>
      <div class="content">
        <div class="content-1" v-if="curMenu===0">
          <div class="resume" v-if="form.intervieweeResume && form.intervieweeResume.length > 0">
            <el-button type="primary" style="position: fixed; right: 60px; top: 90px; z-index: 2;" @click="downloadFile">下载</el-button>
            <el-card v-for="(img, imgIdx) in form.intervieweeResume" :key="imgIdx">
              <img :src="img" style="width: auto; height: auto; max-width: 100%; max-height: 100%;">
            </el-card>
          </div>
          <div class="resume" v-if="form.intervieweeResume && form.intervieweeResume.length === 0">
            <el-card>暂未上传简历</el-card>
          </div>
        </div>
        <div class="content-2" v-if="curMenu===1">
          <el-form label-position="top">
            <div>
              <div v-if="form.process.step <= 5">
                <div v-for="(item, index) in questionList" :key="item.id" class="question-item">
                  <el-form-item :label="(index+1)+'、'+item.questionName">
                    <span v-for="option in item.optionList" :key="option.id">
                      <el-radio v-model="item.answer0" :label="option.optionContent" v-if="option.optionDatatype==='2'" style="margin-right: 20px;" :disabled="!canEditThirdInterview">{{option.optionContent}}</el-radio>
                      <el-input type="textarea" v-model="item.answer1" :placeholder="'请输入'+option.optionContent" rows="3" v-if="option.optionDatatype==='1'" :disabled="!canEditThirdInterview"></el-input>
                    </span>
                  </el-form-item>
                </div>
              </div>
              <div v-if="form.process.step > 5">
                <div v-for="(item, index) in answerListOrganized" :key="item.id" class="question-item">
                  <el-form-item :label="(index+1)+'、'+item.belongQuestion.questionName">
                    <span v-for="answer in answerList" :key="answer.id">
                      <span v-if="answer.belongQuestion.id === item.belongQuestion.id">{{answer.answerContent}}&nbsp;&nbsp;</span>
                    </span>
                  </el-form-item>
                </div>
              </div>
            </div>
            <div v-for="(item, index) in defaultQuestionList" :key="item.id" class="question-item">
              <el-form-item v-if="form.process.step === 4 || form.process.step === 5">
                <template slot="label">{{(questionList.length+index+1)+'、'+item.questionName}}<span style="color: red;"> *</span></template>
                <span v-for="option in item.optionList" :key="option.id">
                  <el-radio v-model="answerForm['answer'+index]" :label="option.id" v-if="option.optionDatatype==='2'" style="margin-right: 20px;" :disabled="!canEditThirdInterview">{{option.optionContent}}</el-radio>
                  <el-input type="textarea" v-model="answerForm['answer'+index]" :placeholder="'请输入'+option.optionContent" rows="3" v-if="option.optionDatatype==='1'" :disabled="!canEditThirdInterview"
                    @focus="autoSaveByTime" @blur="stopAutoSave"></el-input>
                </span>
              </el-form-item>
              <el-form-item v-if="form.process.step > 5">
                <template slot="label">{{(answerListOrganized.length+index+1)+'、'+item.questionName}}<span style="color: red;"> *</span></template>
                <span v-for="option in item.optionList" :key="option.id">
                  <el-radio v-model="form.intervieweeResultStatus" :label="option.id" v-if="option.optionDatatype==='2'" style="margin-right: 20px;" disabled>{{option.optionContent}}</el-radio>
                  <div v-for="result in form.auditResultList" :key="result.id">
                    <el-input type="textarea" v-model="result.auditOperatorOption" :placeholder="'请输入'+option.optionContent" rows="3" v-if="option.optionDatatype==='1' && result.auditStep === 4" disabled></el-input>
                  </div>
                </span>
              </el-form-item>
            </div>
            <el-form-item v-if="form.intervieweeStatus !== '-10' && canEditThirdInterview">
              <el-button type="primary" @click="submitTempAnswerForm(false)" v-if="((form.process.step === 4 || form.process.step === 5) && form.auditResultList[0].auditStep === 4 || (form.process.step === 4 && (form.auditResultList.length === 0 || form.auditResultList[0].auditStep < 4)))">保存</el-button>
              <el-button type="primary" @click="submitAuditForm" v-if="form.process.step === 4 && form.auditResultList[0].auditStep === 4">进入初审</el-button>
            </el-form-item>
            <el-form-item v-if="autoSave">自动保存中……</el-form-item>
          </el-form>
        </div>
        <div class="content-3" v-if="curMenu===2">
          <div class="step-wrapper" v-if="form.process && form.process.stepList">
            <div class="step-item" v-for="(step, stepIndex) in form.process.stepList" :key="step.id" v-show="!((step.step === 2 || step.step === 3) && step.candidatesNamesArr.length === 0)">
              <div class="left default" :class="{done: (step.step < form.process.step || form.process.status === 10), 
                      active: (step.step === form.process.step && form.process.status !== 10),
                      cancel: (step.step === form.process.step && form.intervieweeStatus === '-10')}">
                <div class="line"></div>
                <div class="step-text">{{fieldNameList[stepIndex].stepsName}}</div>
              </div>
              <div class="right">
                <section>
                  <div class="row-1">
                    <div>{{step.stepName}}</div>
                    <span v-if="form.intervieweeStatus === '-10' && step.step === 1">
                      <el-tooltip class="item" effect="dark" :content="'面试取消原因：'+form.intervieweeCancelRemark" placement="bottom">
                        <span>终止面试</span>
                      </el-tooltip>
                    </span>
                    <span class="step-save-btn" v-if="form.intervieweeStatus !== '-10' && form.process.status !== 10">
                      <el-button type="text" style="padding: 0;" @click="showProcessAuditDialog(step.step, false)" 
                        v-if="(step.step === form.process.step - 1) && step.step >= 2 && (form.auditResultList[0].auditOperatorId === userInfo.dingId)">修改
                      </el-button>
                      <el-button type="text" style="padding: 0;" @click="showProcessAuditDialog(step.step, true)" 
                        v-if="isAuth('recruitment:hrrecruitmentauditresult:update') && step.step === form.process.step && form.process.stepList[step.step-1].candidatesId.includes(userInfo.dingId) && (step.step !== 5 && step.step !== 7)">{{step.step === 9 ? '确认到岗' : '处理'}}
                      </el-button>
                      <el-button type="text" style="padding: 0;" @click="showProcessAuditDialog(step.step, true)" 
                        v-if="step.step === form.process.step && modelList[step.step-1].idsArr.includes(userInfo.dingId) && (step.step === 5 || step.step === 7)">处理
                      </el-button>
                    </span>
                  </div>
                  <div v-if="step.step===1">
                    <el-row :gutter="20">
                      <el-col :span="8"><span>姓名：</span><span>{{form.intervieweeName}}</span></el-col>
                      <el-col :span="8"><span>手机：</span><span>{{form.intervieweePhone}}</span></el-col>
                      <el-col :span="8"><span>出生日期：</span><span>{{form.intervieweeBirth}}</span></el-col>
                    </el-row>
                    <el-row :gutter="20">
                      <el-col :span="8"><span>性别：</span><span>{{form.intervieweeSex === 1 ? '男' : form.intervieweeSex === 2 ? '女' : ''}}</span></el-col>
                      <el-col :span="8"><span>应聘岗位：</span><span>{{form.intervieweeJobName}}</span></el-col>
                      <el-col :span="8"><span>学历：</span><span>{{form.intervieweeEducation}}</span></el-col>
                    </el-row>
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <span>接待人：</span>
                        <div v-for="member in step.candidatesNamesArr" :key="member">{{member}}</div>
                      </el-col>
                      <el-col :span="8"><span>面试时间：</span><span>{{form.intervieweeInterviewTime}}</span></el-col>
                      <el-col :span="8"><span>录入人：</span><span v-for="result in form.auditResultList" :key="result.id"><span v-if="result.auditStep === 1">{{result.auditOperatorName}}</span></span></el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="20"><span>备注：</span><span>{{form.intervieweeRemark}}</span></el-col>
                      <el-col :span="4" style="text-align: right;"><el-button type="text" style="padding: 0;" @click="curMenu=0">查看简历<i class="el-icon-caret-right"></i></el-button></el-col>
                    </el-row>
                  </div>
                  <div v-if="step.step > 1">
                    <el-row :gutter="20">
                      <el-col :span="8" style="display: flex;" v-if="fieldNameList[stepIndex].user">
                        <span>{{fieldNameList[stepIndex].user}}：</span>
                        <!-- 流程未处理，显示候选处理人 -->
                        <!-- 非初审终审环节 -->
                        <div v-if="(step.step !== 5 && step.step !== 7) && form.process.step <= step.step && form.process.status !== 10  && form.intervieweeStatus !== '-10' && isAuth('recruitment:hrrecruitmentinterviewee:update')" style="display: flex;">
                          <div v-if="form.intervieweeStatus !== '-10' && form.process.status !== 10 && (step.candidatesNamesArr.length !== 1)">
                            <div class="select-btn" @click="showSelectUserDialog(modelList[step.step-1], step.step-1)"><span><i class="el-icon-plus"></i></span>选择</div>
                          </div>
                          <div v-if="step.candidatesNamesArr.length === 1">
                            <div class="select-btn" @click="showSelectUserDialog(modelList[step.step-1], step.step-1)" v-for="member in step.candidatesNamesArr" :key="member" style="padding: 0;">{{member}}<div class="del" v-if="form.intervieweeStatus !== '-10' && form.process.status !== 10">更换</div></div>
                          </div>
                        </div>
                        <!-- 初审终审环节 -->
                        <div v-if="(step.step === 5 || step.step === 7) && form.process.step <= step.step && form.process.status !== 10  && form.intervieweeStatus !== '-10' && isAuth('recruitment:hrrecruitmentinterviewee:update')" style="display: flex;">
                          <div v-if="step.candidatesNamesArr.length === 0">
                            <div class="select-btn" @click="showSelectUserDialog(modelList[step.step-1], step.step-1)"><span><i class="el-icon-plus"></i></span>选择</div>
                          </div>
                          <div v-if="step.candidatesNamesArr.length > 0">
                            <div class="select-btn" @click="showSelectUserDialog(modelList[step.step-1], step.step-1)" style="padding: 0;">{{step.candidatesNamesArr[0]}}<div class="del" v-if="form.intervieweeStatus !== '-10' && form.process.status !== 10">更换</div></div>
                          </div>
                        </div>
                        <!-- 流程已处理，显示处理人 -->
                        <div v-if="form.process.step > step.step || form.process.status === 10 || form.intervieweeStatus === '-10'">
                          <div v-for="auditResult in form.auditResultList" :key="auditResult.id"><span v-if="auditResult.auditStep===step.step">{{auditResult.auditOperatorName}}</span></div>
                        </div>
                      </el-col>
                      <el-col :span="8" style="display: flex;" v-if="fieldNameList[stepIndex].time">
                        <span>{{fieldNameList[stepIndex].time}}：</span>
                        <span v-for="auditResult in form.auditResultList" :key="auditResult.id">
                          <span v-if="auditResult.auditStep===step.step && step.step !== 8 && step.step !== 9">{{auditResult.auditCreateTime}}&nbsp;&nbsp;</span>
                          <span v-if="auditResult.auditStep===step.step && step.step === 8">{{form.intervieweeEstimateDutytime}}</span>
                          <span v-if="auditResult.auditStep===step.step && step.step === 9">{{form.intervieweeRealDutytime}}</span>
                        </span>
                      </el-col>
                      <el-col :span="8" v-if="fieldNameList[stepIndex].status">
                        <span>{{fieldNameList[stepIndex].status}}：</span>
                        <span v-for="auditResult in form.auditResultList" :key="auditResult.id">
                          <span v-if="auditResult.auditStep===step.step">{{ auditResult.auditStatus==='1' ? '录用' : auditResult.auditStatus==='2' ? '备用' : auditResult.auditStatus==='4' ? '拒绝' : ''}}&nbsp;&nbsp;</span>
                        </span>
                      </el-col>
                    </el-row>
                    <el-row :gutter="20">
                      <el-table
                        v-if="step.step === 6 && !!form.intervieweeSalary"
                        :data="salaryList"
                        :show-header="false"
                        :span-method="arraySpanMethod"
                        border
                        class="salary-table"
                        style="width: 100%; margin-bottom: 20px;">
                        <el-table-column prop="textName" min-width="100" align="center"></el-table-column>
                        <el-table-column prop="time" min-width="120" align="center"></el-table-column>
                        <el-table-column prop="remark" min-width="250" align="center">
                          <template slot-scope="scope">
                            <span>{{scope.row.remark}}<br>{{scope.row.append}}</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="salary" min-width="200" align="center">
                          <template slot-scope="scope">{{form.intervieweeSalaryInfo['salary'+(scope.row.index - 1)]}}</template>
                        </el-table-column>
                      </el-table>
                      <el-col :span="20" v-if="fieldNameList[stepIndex].content">
                        <span>
                          {{fieldNameList[stepIndex].content}}：
                          <span v-for="auditResult in form.auditResultList" :key="auditResult.id">
                            <span v-if="auditResult.auditStep===step.step && step.step!==6">{{ auditResult.auditOperatorOption}}&nbsp;&nbsp;</span>
                          </span>
                          <span v-if="step.step===6">{{ form.intervieweeSalaryInfo.remark}}&nbsp;&nbsp;</span>
                        </span>
                      </el-col>
                      <el-col :span="4" style="text-align: right;" v-if="step.step === 4"><el-button type="text" style="padding: 0; text-decoration: underline;" @click="changePage(1)">查看评价详情</el-button></el-col>
                    </el-row>
                  </div>
                </section>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :title="form.process && form.process.stepList && form.process.stepList[curStep-1] ? form.process.stepList[curStep-1].stepName : ''"
      :visible.sync="processAuditDialogVisible"
      :close-on-click-modal="false"
      width="800px"
      :append-to-body="true">
      <el-form label-width="120px" :model="auditForm" ref="auditForm">
        <div v-if="fieldNameList[curStep-1].content && (curStep === 2 || curStep === 3)">
          <el-form-item :label="fieldNameList[curStep-1].content" :rules="[{ required: true, message: '请输入面试意见', trigger: 'blur' }]">
            <el-input type="textarea" rows="3" v-model="auditForm.exData[0].auditOperatorOption"></el-input>
          </el-form-item>
        </div>
        <div v-if="fieldNameList[curStep-1].status">
          <el-form-item :label="fieldNameList[curStep-1].status">
            <el-radio-group v-model="auditForm.exData[0].auditStatus">
              <el-radio label="1">录用</el-radio>
              <el-radio label="2" v-if="curStep !== 2 && curStep !== 3">备用</el-radio>
              <el-radio label="4">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div v-if="fieldNameList[curStep-1].time">
          <el-form-item :label="fieldNameList[curStep-1].time" :rules="[{ required: true, message: '', trigger: 'blur' }]">
            <el-date-picker
              v-model="auditForm.exData[0].dutytime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </div>
        <div v-if="fieldNameList[curStep-1].salary">
          <el-table
            :data="salaryList"
            :show-header="false"
            :span-method="arraySpanMethod"
            border
            style="width: 100%; margin-bottom: 20px;">
            <el-table-column prop="textName" min-width="100" align="center"></el-table-column>
            <el-table-column prop="time" min-width="120" align="center"></el-table-column>
            <el-table-column prop="remark" min-width="250" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.remark}}<br>{{scope.row.append}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="salary" min-width="200" align="center">
              <template slot-scope="scope">
                <el-input v-model="salaryInfo['salary'+(scope.row.index - 1)]" type="number" min="0" v-if="scope.row.index !== 0"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="fieldNameList[curStep-1].content && (curStep !== 2 && curStep !== 3)">
          <el-form-item :label="fieldNameList[curStep-1].content">
            <el-input type="textarea" v-model="auditForm.exData[0].auditOperatorOption" rows="3" v-if="curStep !== 6"></el-input>
            <el-input type="textarea" v-model="salaryInfo.remark" rows="8" maxlength="1000" show-word-limit v-if="curStep === 6"></el-input>
          </el-form-item>
        </div>
        <div v-if="curStep === 9">
          <el-form-item label="通讯录" :rules="[{ required: true, message: '', trigger: 'blur' }]">
            <el-input v-model="dingUserNameMatch" disabled style="width: 220px;">
              <el-button slot="append" @click="selectDingUsersMatch">选择</el-button>
            </el-input>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <div></div>
        <div>
          <el-button @click="processAuditDialogVisible = false" size="mini">取消</el-button>
          <el-button type="primary" size="mini" @click="submitAuditForm">确定</el-button>
        </div>
      </span>
    </el-dialog>
    <el-dialog
      title="选择操作人"
      :close-on-click-modal="false"
      :visible.sync="userDialogVisible"
      width="520px"
      :append-to-body="true">
      <div>
        <el-tag type="info" v-for="user in curStepUserList" :key="user.emplId" style="margin-right: 20px; cursor: pointer;" @click="chooseUser(user)">{{user.name}}</el-tag>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dingMixin from  '@/mixins/ding'
import formUtil from '@/utils/formUtil'
import {dateUtil} from '@/utils/dateUtil'
export default {
  data () {
    return {
      dialogVisible: false,
      menuList: ['个人简历', '面试评审', '招聘流程'],
      fieldNameList: [
        {stepsName: '录入', user: '接待人', content: '', status: '', time: ''},
        {stepsName: '面试', user: '面试人', content: '面试意见', status: '面试结果', time: '面试时间'},
        {stepsName: '面试', user: '面试人', content: '面试意见', status: '面试结果', time: '面试时间'},
        {stepsName: '面试', user: '面试人', content: '面试意见', status: '面试结果', time: '面试时间'},
        {stepsName: '审核', user: '审核人', content: '审核意见', status: '审核结果', time: ''},
        {stepsName: '回访', user: '操作人', content: '备注', status: '', time: '', salary: ['基础工资', '岗位工资', '星级工资', '绩效工资', '总月薪', '季度工资', '年终奖金', '预估总年薪', '试用期']},
        {stepsName: '录取', user: '审核人', content: '审核意见', status: '面试结果', time: ''},
        {stepsName: '入职', user: '操作人', content: '备注', status: '', time: '预计到岗'},
        {stepsName: '到岗', user: '操作人', content: '', status: '', time: '到岗日期'},
      ],
      salaryList: [
        { index: 0, textName: '职称等级', time: '' , remark: '' },
        { index: 1, textName: '对应月薪', time: '10号' , remark: '基础工资', append: '（固定，和出勤挂钩）' },
        { index: 2, textName: '', time: '' , remark: '岗位工资', append: '（固定，和迟到挂钩）' },
        { index: 3, textName: '', time: '15号（税前）' , remark: '星级工资', append: '（基本固定，特殊清空补充考核项）' },
        { index: 4, textName: '', time: '' , remark: '绩效工资', append: '（70%-110%浮动）' },
        { index: 5, textName: '', time: '总月薪' , remark: '' },
        { index: 6, textName: '季度工资', time: '季度性25号' , remark: '和记考勤挂钩，中途离职不发放' },
        { index: 7, textName: '年终奖金', time: '年底发放' , remark: '中途离职不发放' },
        { index: 8, textName: '预估总年薪', time: '' , remark: '' },
        { index: 9, textName: '试用期', time: '' , remark: '' },
      ],
      salaryInfo: {
        salary0: '',  //基础工资
        salary1: '',  //岗位工资
        salary2: '',  //星际工资
        salary3: '',  //绩效工资
        salary4: '',  //月薪
        salary5: '',  //季度工资
        salary6: '',  //年终奖金
        salary7: '',  //年薪
        salary8: '',   //试用期薪水
        remark: ''
      },
      curMenu: 2,
      form: {
        process: {
          stepList: []
        }
      },
      processAuditDialogVisible: false,
      auditForm: {
        processId: '',
        taskId: '',
        action: true,
        exData: [{
          auditOperatorOption: '',
          auditStatus: '1',
          intervieweeExaminationId: '',
          dutytime: '',             //待入职和入职时使用，填写面试者预计到岗时间和实际到岗时间
          personDingId: '',
        }]
      },
      questionList: [],
      defaultQuestionList: [
        { questionName: '面试结果', optionList: [
          {id: '4', optionContent: '拒绝',  optionScope: '', optionDatatype: '2'},
          {id: '2', optionContent: '备用', optionScope: '', optionDatatype: '2'},
          {id: '1', optionContent: '可录用',  optionScope: '', optionDatatype: '2'}] },
        { questionName: '综合评价', optionList: [{optionContent: '评价', optionScope: '', optionDatatype: '1'},] },
      ],
      answerForm: {
        answer0: '',
        answer1: '',
        id: undefined
      },
      answerList: [],
      ifNext: true,
      curStep: 1,
      autoSave: false,
      timer: null,
      modelList: [],
      userDialogVisible: false,
      curStepUserList: [],
      curIndex: 0,
      dingUserIdMatch: '',
      dingUserNameMatch: '',
      firstEnterAnswerPage: true,
    };
  },
  mixins: [dingMixin],
  props: ['gobackText'],
  components: {
    
  },
  computed: {
    canEditThirdInterview() {
      return this.form.process.stepList[3].candidatesIdsArr.includes(this.userInfo.dingId) && this.form.intervieweeStatus !== '-10'
    },
    canEdit() {
      return this.isAuth('recruitment:hrrecruitmentauditresult:update') && this.isAuth('recruitment:hrrecruitmentauditresult:save')
    },
    answerListOrganized() {
      return this.answerList.filter(item => item.answerDatatype === '2')
    }
  },
  mounted () {
    
  },
  methods: {
    changePage(index) {
      this.curMenu = index
      if(index === 1 && this.firstEnterAnswerPage) {
        this.getAnswerList()
        this.firstEnterAnswerPage = false
      }
    },
    async init(id) {
      await this.getModelList()
      this.curMenu = 2;
      formUtil.resetData(this.answerForm);
      this.answerForm.id = undefined;
      this.firstEnterAnswerPage = true
      await this.getIntervieweeInfo(id)
    },
    async getModelList() {
      let modelList = await this.$httpN.postB('hr/recruitment/model/info?id=3')
      modelList.modelSteps.forEach(item => {
        item.usersArr = []
        item.idsArr = []
        if(item.candidatesId !== '') {
          this.getUserDingIdByRoleId(item)
        }
      })
      this.modelList = modelList.modelSteps
    },
    async getUserDingIdByRoleId(item){
      let roleIdArr = item.candidatesId.split(',')
      let data = await this.$httpN.postB('sys/user/listUserByRoleIds', roleIdArr, false)
      let idsArr = []
      let userArr = []
      roleIdArr.forEach( role => {
        data[role].forEach( dingUser => {
          if(!idsArr.includes(dingUser.emplId)) {
            idsArr.push(dingUser.emplId);
            userArr.push(dingUser)
          }
        })
      })
      item.idsArr = idsArr
      item.usersArr = userArr
    },
    async getIntervieweeInfo(id) {
      let list = await this.$httpN.postB('recruitment/hrrecruitmentinterviewee/info', { id: id })
      list.intervieweeResume = list.intervieweeResume === '' ? [] : JSON.parse(list.intervieweeResume)
      list.intervieweeSalaryInfo = list.intervieweeSalary === '' ? {} : JSON.parse(list.intervieweeSalary)
      list.intervieweeInterviewTime = this.getStandardTime(list.intervieweeInterviewTime)
      list.process.stepList.forEach(item => {
        item.candidatesIdsArr = item.candidatesId === '' ? [] : item.candidatesId.split(",")
        item.candidatesNamesArr = item.candidatesName === '' ? [] : item.candidatesName.split(",")
      })
      this.form = list
      this.form.auditResultList.forEach(result => {
        if(result.auditStep === 4) {
          this.answerForm.answer0 = result.auditStatus
          this.answerForm.answer1 = result.auditOperatorOption
          this.answerForm.id = result.id
        }
      })
      this.dialogVisible = true
    },
    //日期后台返回cst格式转为gmt格式
    getStandardTime(strDate) {
      if(null === strDate || "" === strDate){
        return "";
      }
      var dateStr=strDate.trim().split(" ");
      var strGMT = dateStr[0]+" "+dateStr[1]+" "+dateStr[2]+" "+dateStr[5]+" "+dateStr[3]+" GMT+0800";
      var date = new Date(Date.parse(strGMT));
      var y = date.getFullYear();
      var m = date.getMonth() + 1;  
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();  
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      h = h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();  
      minute = minute < 10 ? ('0' + minute) : minute;
      var second = date.getSeconds();
      second = second < 10 ? ('0' + second) : second;
      
      return y+"-"+m+"-"+d+" "+h+":"+minute+":"+second;
    },
    async getAnswerList() {
      this.answerList = [];
      let {list} = await this.$httpN.postB('recruitment/hrrecruitmentanswer/list', {answerBelongInterview: this.form.id, limit: 999})
      if(list) {
        this.answerList = list;
        this.getQuestionList()
      }
    },
    async getQuestionList() {
      let {list} = await this.$httpN.postB('recruitment/hrrecruitmentquestion/list', { questionBelongId: this.form.intervieweeExaminationId, limit: 999 })
      list.forEach( question => {
        question.answer0 = ''
        question.answer1 = ''
        this.answerList.forEach( oldAnswer => {
          if(question.id === oldAnswer.answerBelongQuestion && oldAnswer.answerDatatype === '2') question.answer0 = oldAnswer.answerContent
          if(question.id === oldAnswer.answerBelongQuestion && oldAnswer.answerDatatype === '1') question.answer1 = oldAnswer.answerContent
        })
      })
      this.questionList = list;
    },
    //三面评价每5秒保存一次
    autoSaveByTime() {
      if((this.form.process.step === 4 || this.form.process.step === 5) && this.form.auditResultList[0].auditStep === 4) {
        this.timer = setInterval(() => {
          this.submitTempAnswerForm()
        }, 5000);
      } else if(this.form.process.step === 4 && (this.form.auditResultList.length === 0 || this.form.auditResultList[0].auditStep < 4)) {
        this.timer = setTimeout(() => {
          this.submitTempAnswerForm(false)
        }, 5000);
      }
    },
    stopAutoSave() {
      clearInterval(this.timer);    
      this.timer = null;
      if(((this.form.process.step === 4 || this.form.process.step === 5) && this.form.auditResultList[0].auditStep === 4) || (this.form.process.step === 4 && (this.form.auditResultList.length === 0 || this.form.auditResultList[0].auditStep < 4))) {
        this.timer = setTimeout(() => {
          this.submitTempAnswerForm(true)
        }, 5000);
      }
    },
    async submitTempAnswerForm(auto=true) {
      let answerArr = [];
      let firstSave = this.answerList.length === 0 ? true : false
      if (firstSave) {
        this.questionList.forEach( question => {
          if(question.answer0 === '') {
            answerArr.push({
              answerBelongQuestion: question.id,
              answerBelongInterview: this.form.id,
              answerDatatype: '2',
              answerContent: question.answer0,
              answerScope: ''
            })
          }
          question.optionList.forEach( answer => {
            if(answer.optionContent === question.answer0 && answer.optionDatatype === '2' && (question.answer0 !== '')) {
              answerArr.push({
                answerBelongQuestion: question.id,
                answerBelongInterview: this.form.id,
                answerDatatype: answer.optionDatatype,
                answerContent: question.answer0,
                answerScope: answer.optionScope
              })
            }
            if(answer.optionDatatype === '1') {
              answerArr.push({
                answerBelongQuestion: question.id,
                answerBelongInterview: this.form.id,
                answerDatatype: answer.optionDatatype,
                answerContent: question.answer1,
                answerScope: answer.optionScope
              })
            }
          })
        })
      } else {
        this.questionList.forEach( question => {
          this.answerList.forEach( oldAnswer => {
            if(question.id === oldAnswer.answerBelongQuestion && oldAnswer.answerDatatype === '2') oldAnswer.answerContent = question.answer0
            if(question.id === oldAnswer.answerBelongQuestion && oldAnswer.answerDatatype === '1') oldAnswer.answerContent = question.answer1
          })
        })
        answerArr = this.answerList
      }
      if(answerArr.length > 0) {
        if(!await this.$httpN.postB(firstSave ? 'recruitment/hrrecruitmentanswer/save' : 'recruitment/hrrecruitmentanswer/update', answerArr, false)) return
      }
      if(!await this.$httpN.postB('recruitment/hrrecruitmentauditresult/save', {
        id: this.answerForm.id,
        auditInterviewId: this.form.id,
        auditProcessId: this.form.process.id,
        auditStep: 4,
        auditOperatorOption: this.answerForm.answer1,
        auditStatus: this.answerForm.answer0,
      })) return
      if(!auto) {
        formUtil.submitSuccess('保存成功');
        this.reload(this.form.id);
      } else {
        this.autoSave = true;
        this.reload(this.form.id);
        setTimeout(() => {
          this.autoSave = false;
        }, 1000)
      }
      this.getAnswerList()
    },
    selectDingUsers(id, name, ids, names, item, num){
      if(this.form.process.step > item.step) return
      this.complexPicker(num, [], item[ids]).then((data)=>{
        item[ids] = data.map(item => item.emplId);
        item[names] = data.map(item => item.name)
        item[name] = item[names].join(',');
        item[id] = item[ids].join(',')
        this.submitOperator(item)
      })
    },
    selectDingUsersMatch() {
      this.complexPicker(1, [], [this.dingUserIdMatch]).then((data)=>{
        this.dingUserNameMatch = data.map(item => item.name).join(',');
        this.dingUserIdMatch = data.map(item => item.emplId).join(',')
      })
    },
    async submitOperator(item) {
      if(!await this.$httpN.postB('recruitment/hrrecruitmentinterviewee/update', {
        id: this.form.id,
        stepList: [item]
      })) return
      formUtil.submitSuccess('保存成功');
      this.reload(this.form.id)
    },
    showProcessAuditDialog(step, ifNext) {
      this.curStep = step
      this.ifNext = ifNext;
      this.dingUserIdMatch = '';
      this.dingUserNameMatch = '';
      formUtil.resetData(this.salaryInfo);
      this.auditForm = {
        processId: this.form.process.id,
        taskId: this.form.process.taskId,
        action: true,
        exData: []
      };
      if(ifNext) {
        this.auditForm.exData.push({
          auditOperatorOption: '',
          auditStatus: '',
          intervieweeExaminationId: '',
          dutytime: this.curStep === 9 ? this.form.intervieweeEstimateDutytime : '',
          personDingId: ''
        })
      } else {
        let lastObj = this.form.auditResultList[0]
        if(lastObj.auditOperatorOption !== '' && step === 6) this.salaryInfo = JSON.parse(lastObj.auditOperatorOption)
        this.auditForm.exData.push({
          id: lastObj.id,
          auditOperatorOption: lastObj.auditOperatorOption,
          auditStatus: lastObj.auditStatus,
          dutytime: this.curStep === 8 ? this.form.intervieweeEstimateDutytime : '',
          intervieweeExaminationId: '',
          personDingId: ''
        })
      }
      
      if(this.fieldNameList[step-1].status) this.auditForm.exData[0].auditStatus = '1';
      step === 4 ? this.changePage(1) : this.processAuditDialogVisible = true
    },
    async submitAuditForm() {
      //进入初审
      if(this.ifNext && this.form.process.step === 4) {
        this.auditForm = {
          processId: this.form.process.id,
          taskId: this.form.process.taskId,
          action: true,
          exData: []
        };
        this.auditForm.exData.push({
          id: this.form.auditResultList[0].id,
          auditOperatorOption: this.answerForm.answer1,
          auditStatus: this.answerForm.answer0,
          intervieweeExaminationId: this.form.intervieweeExaminationId,
          dutytime: '',
        })
      }
      if((this.form.process.step === 4) && !this.answerForm.answer0) return this.$message.error("请选择面试结果")
      if((this.curStep === 2 || this.curStep === 3 || this.curStep === 4) && !this.auditForm.exData[0].auditOperatorOption) return this.$message.error("请输入面试意见")
      if((this.form.process.step === 4) && !this.answerForm.answer1) return this.$message.error("请输入面试意见")
      if(this.curStep === 6) this.auditForm.exData[0].auditOperatorOption = JSON.stringify(this.salaryInfo)
      if((this.curStep === 8) && !this.auditForm.exData[0].dutytime) return this.$message.error("请选择预计到岗日期")
      if((this.curStep === 9) && !this.auditForm.exData[0].dutytime) return this.$message.error("请选择到岗日期")
      if((this.curStep === 9) && this.auditForm.exData[0].dutytime) {
        let factTime = new Date(this.auditForm.exData[0].dutytime+' 00:00:00').getTime()
        let nowTime = new Date(dateUtil.thisDay()+' 00:00:00').getTime()
        if(nowTime - factTime >= 15*24*60*60*1000 || nowTime - factTime < 0) return this.$message.error("到岗日期应在过去15天内")
      }
      if(this.curStep === 9 && !this.dingUserIdMatch) return this.$message.error("请选择钉钉通讯录用户进行匹配")
      this.auditForm.action = this.auditForm.auditStatus === '4' ? false : true;
      if(this.curStep === 9) this.auditForm.exData[0].personDingId = this.dingUserIdMatch;
      if(this.ifNext) {
        if(!await this.$httpN.postB('audit/process/audit', this.auditForm)) return
      } else {
        if(!await this.$httpN.postB('recruitment/hrrecruitmentauditresult/update', {
          id: this.auditForm.exData[0].id,
          processId: this.auditForm.processId,
          auditOperatorOption: this.auditForm.exData[0].auditOperatorOption,
          dutytime: this.auditForm.exData[0].dutytime,
        })) return
      }
      formUtil.submitSuccess('保存成功');
      this.reload(this.form.id);
      this.processAuditDialogVisible = false;
    },
    reload(id) {
      if(id) this.getIntervieweeInfo(id)
      this.$emit("refresh");
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      //合并列
      if(rowIndex === 0 || rowIndex === 8 || rowIndex === 9) {
        if(columnIndex === 0) {
          return [1, 3]
        } else if(columnIndex === 1 || columnIndex === 2) {
          return [0, 0]
        }
      }
      //合并列
      if(rowIndex === 5) {
        if(columnIndex === 1) {
          return [1, 2]
        } else if(columnIndex === 2) {
          return [0, 0]
        }
      }
      //合并行
      if(columnIndex === 0) {
        if(rowIndex === 1) {
          return {
            rowspan: 5,
            colspan: 1
          }
        } else if(rowIndex > 1 && rowIndex <= 5) {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
      //合并行
      if(columnIndex === 1) {
        if(rowIndex === 1 || rowIndex === 3) {
          return {
            rowspan: 2,
            colspan: 1
          }
        } else if(rowIndex === 2 || rowIndex === 4) {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    showSelectUserDialog(step, index) {
      if(this.form.intervieweeStatus === '-10') return
      this.curStepUserList = step.usersArr
      this.curIndex = index
      this.userDialogVisible = true
    },
    chooseUser(user) {
      this.form.process.stepList[this.curIndex].candidatesId = user.emplId
      this.form.process.stepList[this.curIndex].candidatesName = user.name
      this.submitOperator(this.form.process.stepList[this.curIndex])
      this.userDialogVisible = false
    },
    downloadFile: function () {
      this.form.intervieweeResume.forEach((url, index) => {
        if(!url) return
        url += '?id=1'
        let fileName = this.form.intervieweeName + '-' + this.form.intervieweeJobName
        if(this.form.intervieweeResume.length > 1) fileName += '-' + (index + 1)
        var x = new XMLHttpRequest();
        x.open("GET", url, true);
        x.responseType = 'blob';
        x.onload = function() {
          var url = window.URL.createObjectURL(x.response)
          var a = document.createElement('a');
          a.href = url
          a.download = fileName;
          a.click()
        }
        x.send();
      })
    },
  }
}
</script>

<style lang='scss' scoped>
.detail-dialog {
  /deep/ .el-dialog__header, /deep/ .el-dialog__body {
    padding: 0;
  }
  .nav-bar {
    position: relative;
    width: 100%;
    height: 50px;
    border-bottom: 1px solid #DCDFE6;
    .back {
      position: absolute;
      left: 20px;
      top: 7px;
      cursor: pointer;
    }
    .nav-wrapper {
      display: flex;
      justify-content: center;
      .menu-wrapper {
        display: inline-block;
        margin-right: 16px;
        &:last-child {
          margin-right: 0;
        }
        .menu {
          height: 50px;
          line-height: 50px;
          margin: 0 16px;
          text-align: center;
          cursor: pointer;
          font-size: 16px;
          color: #6E6E71;
          font-weight: 700;
        }
        .active {
          color: #1989FA;
          border-bottom: 2px solid #1989FA;
        }
      }
    }
  }
  .content {
    height: calc(100vh - 50px);
    overflow: auto;
    padding: 20px;
    .content-1 {
      .resume {
        .el-card {
          margin-bottom: 20px;
          position: relative;
          text-align: center;
          &:hover i {
            display: block;
          }
          i {
            display: none;
            position: absolute;
            right: 10px;
            top: 10px;
            background-color: #409eff;
            color: #FFF;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            line-height: 20px;
            text-align: center;
            cursor: pointer;
          }
        }
      }
    }
    .content-2 {
      border: 1px solid #DCDFE6;
      background-color: #f5f5f7;
      padding: 20px;
    }
    .content-3 {
      height: auto;
      .step-wrapper {
        display: flex;
        flex-flow: column;
        .step-item {
          display: flex;
          &:last-child .line {
            display: none;
          }
          &:hover .step-save-btn {
            display: block;
          }
          .left {
            width: 40px;
            position: relative;
            .line {
              width: 6px;
              height: 100%;
              top: 0;
              left: 17px;
              background-color: #D3D3D4;
              position: absolute;
            }
            .step-text {
              width: 40px;
              height: 40px;
              line-height: 34px;
              text-align: center;
              border-radius: 50%;
              border: 6px solid;
              position: relative;
              background-color: #FFF;
              transition: .15s ease-out;
              font-size: 10px;
            }
          }
          .left.default {
            color: #D3D3D4;
          }
          .left.done {
            color: #409EFF;
            .line {
              background-color: #409EFF;
            }
          }
          .left.active {
            color: #E6A23C;
            .line {
              background-color: #E6A23C;
            }
          }
          .left.cancel {
            color: #F56C6C;
            .line {
              background-color: #F56C6C;
            }
          }
          .right {
            flex: 1;
            padding-left: 20px;
          }
        }
      }
      section {
        border: 1px solid #DCDFE6;
        padding: 20px;
        margin-bottom: 30px;
        .row-1 {
          font-size: 14px;
          font-weight: bolder;
          margin-bottom: 10px;
          display: flex;
          justify-content: space-between;
          .step-save-btn {
            display: none;
            font-size: 12px;
            font-weight: normal;
            margin-left: 20px;
            text-align: right;
          }
        }
        .el-row {
          line-height: 28px;
          margin-bottom: 10px;
          &:last-child {
            margin-bottom: 0;
          }
          .el-col {
            display: flex;
            flex-wrap: wrap;
          }
        }
        table.table {
          width: 100%;
          text-align: center;
          border: 1px solid #666666;
          border-collapse: collapse;
        }
        table.table td {
          border: 1px solid #666666;
          padding: 8px;
        }
        .select-btn{
          float:left;
          font-weight: normal;
          margin-right: 5px;
          margin-bottom: 5px;
          width: 80px;
          height: 28px;
          border-radius: 30px;
          background: #FAFAFA;
          border: 1px solid #ECECEC;
          position: relative;
          padding-left: 21px;
          line-height: 28px;
          color: #7982A7;
          font-size: 12px;
          text-align: center;
          cursor: pointer;
          span{
            position: absolute;
            top: 1px;
            left: 1px;
            display:block;
            height: 24px;
            width: 24px;
            background: #CACACA;
            color: white;
            border-radius: 50%;
            text-align: center;
            line-height: 24px;
            img{
              width: 24px;
              height: 24px;
              border-radius: 50%;
            }
          }
          .del{
            position: absolute;
            top:0;
            left: 0;
            width: 100%;
            height: 100%;
            border-radius: 30px;
            color: white;
            text-align: center;
            background:rgba(130, 130, 130, 0.9);
            display: none;
          }
          &:hover{
            .del{
              display: block;
            }
          }
        }
      }
    }
  }
}
.salary-table {
  border:  1px solid #000;
  /deep/ th, /deep/ td {
    border-color: #000;
  }
}
</style>